package priorityQueue;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-09-19
 * Time: 8:21
 */
class IntCmp implements Comparator<Integer> {
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}
public class Test2 {

    public int[] smallestK(int[] arr, int k) {
        int[] ret = new int[k];
        if(arr == null || k == 0) {
            return ret;
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, new IntCmp());
        for(int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }

        for(int i = k; i < arr.length; i++) {
            int peekVal = priorityQueue.peek();
            if(arr[i] < peekVal) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        for(int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }

    public int[] smallestK1(int[] arr, int k) {
        PriorityQueue<Integer> priorityqueue = new PriorityQueue<>();
        for(int i = 0; i < arr.length; i++) {
            priorityqueue.offer(arr[i]);
        }

        int[] ret = new int[k];
        for(int i = 0; i < k; i++) {
            ret[i] = priorityqueue.poll();
        }

        return ret;
    }
    //直接插入排序：
    public static void insertSort(int[] array) {
        for (int i = 1; i < array.length; i++) {
            int tmp = array[i];
            int j = i - 1;
            for (; j >= 0 ; j--) {
                if(array[j] > tmp) {
                    array[j + 1] = array[j];
                } else {
                    array[j + 1] = tmp;
                    break;
                }
            }
            array[j + 1] = tmp;
        }
    }
    public static void main(String[] args) {
        int[] array = {10, 2, 5, 7, 3};
        System.out.println("直接插入排序前：");
        for(int x : array) {
            System.out.print(x + " ");
        }
        System.out.println();
        insertSort(array);
        System.out.println("直接插入排序后：");
        for(int x : array) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
}
